package com.scnu.yxp.travelapp.view;

import com.scnu.yxp.travelapp.R;

import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MyListView extends ListView implements OnScrollListener {
	private Context context;
	//使用layoutinflater来加载界面
	private LayoutInflater inflater;
	//滑动监听器
	private OnScrollListener onScrollListener;
	//下拉更新的界面
	private View pullToRefreshHeader;
	//记录header的paddingTop
	private int headerOriginalPaddingTop;
	//header的高度
	private int headerHeight;
	//界面中的控件
	private TextView pullRefreshState;
	//下拉更新的状态
	private static final int Tag_To_Refresh = 1;
	private static final int Pull_To_Refresh = 2;
	private static final int Release_To_Refresh = 3;
	private static final int Refreshing = 4;
	//下拉更新的监听器
	private OnHeaderRefreshListener onHRefreshListener;
	//上拉更新的状态
	private static final int Refreshing_footer = 1;
	private static final int Hide_footer = 0;
	//上拉加载的view
	private View footerLoadView;
	//上拉加载的控件
	private TextView footerRefreshState;
	//上拉加载的回调接口
	private OnFooterRefreshListener onFRefreshListener;
	//是否最后一行
	private boolean isLastRow = false;
	//是否第一行
	private boolean isFirstRow = true;
	
	//header和footer滑动的状态
	private int scrollState = Tag_To_Refresh;
	private int scrollState_footer = Hide_footer;
	//listview的滑动状态
	private int currentState ;
	//listview是否停止滑动
	private boolean isStopScroll = true;
	//记录刚按下时的Y左边
	private float lastY = 0;
	//是否没有数据可以加载了
	private boolean isNothingToLoad = false;
	//是否要上拉加载数据
	private boolean wantToLoad = false;

	public MyListView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		this.context = context;
		init();
	}

	public MyListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		init();
	}

	public MyListView(Context context) {
		super(context);
		this.context = context;
		init();
	}
	//初始化加入header,但是要隐藏它，只有当下滑时才随着手指下滑
	public void init()
	{
		//可使用inflater = (LayoutInflater)context.getSystemService(CONTEXT.LAYOUT_INFLATER_SERVICE);
		inflater = LayoutInflater.from(context);
		//加载界面
		pullToRefreshHeader = inflater.inflate(R.layout.mylistview_header, null);
		footerLoadView = inflater.inflate(R.layout.mylistview_footer, null);
		pullRefreshState = (TextView)pullToRefreshHeader.findViewById(R.id.pull_state);
		footerRefreshState = (TextView)footerLoadView.findViewById(R.id.state);
		addHeaderView(pullToRefreshHeader);
		headerOriginalPaddingTop = pullToRefreshHeader.getPaddingTop();
		//加入滑动监听，一定要调用父类的方法，否则无法成功，因为地下重写了setOnScrollListener
		super.setOnScrollListener(this);
		//测量header的高度
		measure(pullToRefreshHeader);
		headerHeight = pullToRefreshHeader.getMeasuredHeight();
		pullToRefreshHeader.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				//开始一个加载的异步任务
				if(scrollState != Refreshing)
				{
					LoadTask task = new LoadTask();
					task.execute("");
				}
			}
		});
		//无滚动条
		if (isVerticalFadingEdgeEnabled()) {
            setVerticalScrollBarEnabled(false);
        }
		setScrollbarFadingEnabled(true);
	}

	//测量view的长宽
	public void measure(View child)
	{
		//取得view的空间
		ViewGroup.LayoutParams params= child.getLayoutParams();
		if(params == null)
		{
			params = new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		}
		//取得视图的宽度
		 int childWidthSpec = ViewGroup.getChildMeasureSpec(0,
	                0 + 0, params.width);
		int childHeight = params.height;
		int childHeightSpec ;
		if(childHeight > 0)
		{
			//高度只能达到这么多
			childHeightSpec = MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY);
		}else{
			//高度未指定
			childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
		}
		child.measure(childWidthSpec, childHeightSpec);
	}

	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		//记下按下的点
		float y = event.getY();
		//松手的动作
		if(event.getAction() == MotionEvent.ACTION_UP)
		{
			if(getFirstVisiblePosition() == 0)
			{
				if(scrollState == Release_To_Refresh)
				{
					//开始一个加载的异步任务
					LoadTask task = new LoadTask();
					task.execute("");
				}else if(scrollState == Pull_To_Refresh){
					resetHeader();
					setSelection(1);
				}
			}
		}else
		//按下的动作
		if(event.getAction() == MotionEvent.ACTION_DOWN)
		{
			lastY = y;
			wantToLoad = true;
		}else
		//移动的动作
		if(event.getAction() == MotionEvent.ACTION_MOVE)
		{
			if(scrollState != Refreshing && (getFirstVisiblePosition() == 1 
					|| getFirstVisiblePosition() == 0 ))
			{
				setHeaderPadding(event);
			}
			
		}
		return super.onTouchEvent(event);
	}
	
	//重置header的距离
	public void resetHeader()
	{
		pullToRefreshHeader.setPadding(pullToRefreshHeader.getPaddingLeft(), headerOriginalPaddingTop, 
				pullToRefreshHeader.getPaddingRight(), pullToRefreshHeader.getPaddingBottom());
	}
	public void setHeaderPadding(MotionEvent event)
	{
		//记录上一次的按下的点的数量
		int pointerCount = event.getHistorySize();
		for(int i = 0; i < pointerCount; i++)
		{
            int historicalY = (int) event.getHistoricalY(i);
            //设置滑动的距离
            int topPadding = (int) (((historicalY - lastY)- headerHeight) / 1.7);
            pullToRefreshHeader.setPadding(pullToRefreshHeader.getPaddingLeft(), topPadding,
                    pullToRefreshHeader.getPaddingRight(), pullToRefreshHeader.getPaddingBottom());
            //当下拉了一段距离则改变内容
            if(topPadding < 25)
            {
        		scrollState = Pull_To_Refresh;
        		pullRefreshState.setText("下拉更新");
            }else if(topPadding >= 25)
            {
            	scrollState = Release_To_Refresh;
            	pullRefreshState.setText("松手更新");
            }
		}
	}

	@Override
	public void setOnScrollListener(OnScrollListener l) {
		onScrollListener = l;//加入监听器
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		//记录当前的listview滑动情况
		currentState = scrollState;
		if(scrollState == SCROLL_STATE_FLING)
		{
			isStopScroll = false;
		}
		if(scrollState == SCROLL_STATE_IDLE)
		{
			isStopScroll = true;
		}
		if(onScrollListener != null)
		{
			onScrollListener.onScrollStateChanged(view, scrollState);
		}
	}
	
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {
		if(currentState == SCROLL_STATE_FLING && scrollState != Release_To_Refresh 
				&& getFirstVisiblePosition() == 0)
		{
			resetHeader();
			setSelection(1);
		}
		if(currentState == SCROLL_STATE_FLING && scrollState == Release_To_Refresh 
				&& getFirstVisiblePosition() == 0)
		{
			//开始一个加载的异步任务
			LoadTask task = new LoadTask();
			task.execute("");
		}
		//判定是否滑到了顶部
		if(firstVisibleItem == 1)
		{
			isFirstRow = true;
		}
		//判定是否滑到了底部
		if(firstVisibleItem + visibleItemCount >= totalItemCount && totalItemCount > 0)
		{
			isLastRow = true;
			if(currentState != SCROLL_STATE_TOUCH_SCROLL && !isNothingToLoad && wantToLoad)
			{
				if(scrollState_footer == Hide_footer)
				{
					LoadTask_footer task = new LoadTask_footer();
					task.execute("");
				}else{
					wantToLoad = false;
				}
			}
		}else{
			isLastRow = false;
		}
		if(onScrollListener != null)
		{
			onScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
		}
	}
	
	//屏蔽HOME键4的方法
	@Override
	protected void onAttachedToWindow() {
		super.onAttachedToWindow();
		setSelection(1);
	}

	@Override
	public void setAdapter(ListAdapter adapter) {
		super.setAdapter(adapter);
		setSelection(1);
	}
	
	public void setOnHeaderRefreshListener(OnHeaderRefreshListener r)
	{
		onHRefreshListener = r;
	}
	
	public void setOnFooterRefreshListener(OnFooterRefreshListener r)
	{
		onFRefreshListener = r;
	}

	//下拉刷新回调接口
	public interface OnHeaderRefreshListener
	{
		//更新的回调接口
		public void onRefresh();
	}
	//上拉刷新回调接口
	public interface OnFooterRefreshListener
	{
		public boolean onRefresh();
	}
	//header的异步加载任务
	class LoadTask extends AsyncTask<Object, Object, Object>
	{

		@Override
		protected Object doInBackground(Object... arg0) {
			
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Object result) {
			//结束之后就回复原始的样貌
			scrollState = Tag_To_Refresh;
			resetHeader();
			setSelection(1);
			pullRefreshState.setText("点击更新");
		}

		@Override
		protected void onPreExecute() {
			onHRefreshListener.onRefresh();
			//在加载开始前将header的位置调好
			scrollState = Refreshing;
			resetHeader();
			setSelection(0);
			pullRefreshState.setText("正在更新");
		}
	}
	//footer的加载异步任务
	class LoadTask_footer extends AsyncTask<Object, Object, Object>
	{

		@Override
		protected Object doInBackground(Object... arg0) {
			
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Object result) {
			//如果没有数据则设置无法继续上拉加载
			if(isNothingToLoad)
			{
				footerRefreshState.setText("——暂无数据——");
			}else{
				removeFooterView(footerLoadView);
				scrollState_footer = Hide_footer;
			}
			wantToLoad = false;
		}

		@Override
		protected void onPreExecute() {
			if(!onFRefreshListener.onRefresh())
			{
				isNothingToLoad = true;
			}
			scrollState_footer = Refreshing_footer;
			addFooterView(footerLoadView);
		}
		
	}
}
